package com.tgy.helloworld.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tgy.helloworld.service.News;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/***
 * @ClassName: HelloBoot
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 20:41 2021/12/22
 * @version : V1.0
 */

//自动专配
@RestController
@Slf4j
@RequiredArgsConstructor
//@RefreshScope
public class HelloBoot {

    private final RestTemplate restTemplate;
    private final News news;

    @Value("${test.el.list:1}")
    private List<String> list;


    @Value("#{'${test.el.list:你好,我好}'.split(',')}")
    private List<String> el;

    @RequestMapping("/aa")
    public String aa() {
        //String forObject = restTemplate.getForObject("http://220.179.8.182:8080/c/ahhgxx/", String.class);

        //创建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //String token = "Jeecms-Auth-Token";
        //String tokenV = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJzeXN0ZW0iLCJjcmVhdGVkIjoxNjg4MDg2MjQ2NjcyLCJ1c2VyU291cmNlIjoiYWRtaW4iLCJleHAiOjE2ODgwODc0NDZ9.CkBuFrCRh1jEPbJ4L6CNmGQLV23QgDhn6BpuoaqrnF2w02miU9gT3c7gK_M_ivb50myXLHujr3W2jaXWh01Byw";
        String cookie = "cookie";
        String cookieV = "JIDENTITY=8a44c2f5-9339-4bd3-830b-ecc6a34bc9a2; JSESSIONID=0ADCAEA01808397556C1003574A48610";
        String site = "Siteid";
        String siteV = "102"; //需要修改为默认指定的站点
        //headers.add(token,tokenV);
        headers.add(site,siteV);
        headers.add(cookie,cookieV);
        JSONObject post = JSONObject.parseObject("{\"json\":{\"pics\":[],\"xinwenliebiaotu\":\"\",\"xinwenfenxiangtu\":\"\",\"shoujibannertu\":\"\",\"shoujiliebiaotu\":\"\",\"biaotitu\":\"\",\"neirongtu\":\"\",\"leixingtu\":\"\",\"txt3\":\"JTNDcCUzRTExMTElM0MvcCUzRQ==\"},\"modelId\":912,\"modelName\":\"新闻\",\"channelId\":2341,\"title\":{\"titleColor\":\"#666666\",\"titleIsBold\":true,\"title\":\"你好你好你好\"},\"shortTitle\":\"1111\",\"releaseTime\":\"2023-06-30 09:55:22\",\"author\":\"\",\"description\":\"1111\",\"resource\":\"\",\"contentSourceId\":{\"sourceLink\":\"\",\"sourceName\":\"人民网\"},\"contentTag\":\"\",\"releaseTerrace\":[\"releasePc\",\"releaseWap\",\"releaseApp\",\"releaseMiniprogram\"],\"tplPc\":\"\",\"tplMobile\":\"\",\"allowComment\":1,\"viewControl\":1,\"outLink\":{\"isNewTarget\":false,\"outLink\":\"\"},\"\":\"\",\"type\":5}");
        HttpEntity<String> entity = new HttpEntity<String>(post.toString(), headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost:8083/cmsmanager/content", entity, String.class);
        String body = responseEntity.getBody();
        return body;
    }

    @RequestMapping("/bb")
    public String bb() throws UnsupportedEncodingException {
        log.info("bb启动");
        news.add();
        return list.toString();
    }

    @RequestMapping("/cc")
    public String cc() throws UnsupportedEncodingException {
        log.info("cc启动");
        news.deal();
        return el.toString();
    }

    @RequestMapping("/dd")
    public String dd()  {
        log.info("dd启动");
        return el.toString();
    }

    @RequestMapping("/ff")
    public String ff()  {
        log.info("ff");
        return list.toString();
    }


    /**
     * @Param 导入导出相关操作
     * @Description: TODO
     * @auther: Tanggy3
     * @date: 9:30 2024/2/27
     * @return:
     */
/*    @PostMapping("/export")
    @ApiOperation(value = "导出表格", notes = "导出表格")
    public void getexe(HttpServletResponse response) throws IOException {
        Search search = new Search();
        search.setSize(20);
        search.setCurrent(1);
        IPage<School> schoolIPage = schoolService.listPage(search);

        //文件名需要这样写，不能在setHeader直接写中文名，否则下载的文件名字为空，只有后缀
        String fileName = new String("aa.xlsx".getBytes(), StandardCharsets.ISO_8859_1);
        response.setContentType("application/msexcel");
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        // 如果不用模板的方式导出的话，是doWrite
        EasyExcel.write(response.getOutputStream(), School.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("学校信息")
                .doWrite(schoolIPage.getRecords());
    }


    @ApiOperation("从Excel导入学校信息")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> importMemberList(@RequestPart("file") MultipartFile file) {

        int b = 0;
        try {
            List<School> schools = new ArrayList<>();
            List<School> imports = EasyExcel.read(file.getInputStream())
                    .head(School.class)
                    .sheet("学校信息")
                    .doReadSync();
            imports.forEach((bean) -> {
                if (bean.getName() != null && $.isNotEmpty(bean.getName())) {
                    schools.add(shift(bean));
                }
            });
            if ($.isNotEmpty(schools)) {
                b = this.schoolMapper.insertOrUpdateBatch(schools);
            }
        } catch (Exception e) {
            log.error("导入学校出错===>", e);
            return Result.fail("导入学校出错,可能原因：1：导入表格中的必填项未填写。请检查数据后重试！");
        }
        return Result.data(b);
    }*/



    @RequestMapping(value = "/handleExecl", method = RequestMethod.POST)
    @ResponseBody
    public String aaaa(@RequestPart("file") MultipartFile file,@RequestParam("type") String type ,@RequestParam("name")String name ,@RequestParam("out")String out) {

        try {
            Workbook workbook = new XSSFWorkbook(file.getInputStream());
            // 创建一个 FileWriter 对象，用于将结果写入到一个 txt 文件
            String rname = name +".md";
            FileWriter writer = new FileWriter(rname);

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 迭代每一行，从第二行开始（第一行通常是标题）
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);

                // 获取国家名称，假设它在第一列
                String country = row.getCell(0).getStringCellValue();
                if (country.isEmpty())
                    continue;

                // 迭代每一个单元格，从第二列开始（第一列通常是国家名称）
                for (int cellIndex = 1; cellIndex < row.getLastCellNum(); cellIndex++) {
                    Cell cell = row.getCell(cellIndex);

                    // 获取年份
                    Cell yearCell = sheet.getRow(0).getCell(cellIndex);
                    int year;
                    if (yearCell.getCellType() == CellType.NUMERIC) {
                        year = (int) yearCell.getNumericCellValue();
                    } else {
                        // 如果年份是字符串，尝试将其转换为整数
                        try {
                            year = Integer.parseInt(yearCell.getStringCellValue());
                        } catch (IllegalStateException e) {
                            // 如果转换失败，跳过当前单元格
                            continue;
                        }
                    }
                    double numericCellValue;
                    try {
                        numericCellValue = cell.getNumericCellValue();
                    } catch (IllegalStateException e) {
                        // 如果转换失败，跳过当前单元格
                        continue;
                    }



                    // 输出格式化的信息
                    // 格式化信息
                    //String output = String.format("%s %d 年%s %.10f %s%n", country, year,out,numericCellValue, type);
                    String output = String.format("%d年%s%.10f%n", year, country,numericCellValue);
                    System.out.printf("%d年%s%.10f%n", year, country,numericCellValue);
                    // 将结果写入到文件
                    writer.write(output);
                }
            }

            writer.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }

}
